import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from user.models import User
from order.models import Order
from evaluation.models import Evaluation
from util.token_tools import make_token, check_login


# 评论详情视图(无数据)
def evaluation_detail_view(request, order_code):
    return render(request, 'evaluation.html', {"order_code": order_code})


# 评论列表视图(无数据)
def evaluation_list_view(request):
    return render(request, 'evaluation_list.html')


@check_login
def reqeust_list_view(request, username):
    user = request.login_user
    if user.user_name != username:
        return JsonResponse({'code': 10102, 'error': '请重新登录'})
    else:
        print("**************************")
        user = User.objects.get(user_name=username)
        order_list = Order.objects.filter(user=user)
        print(f"order_list ={order_list}")
        list = []
        for item in order_list:
            print(f"item ={item}")
            evaluation_list = Evaluation.objects.filter(order=item)
            for item in evaluation_list:
                dict = {
                    'content': item.content,
                    'order_code': item.order.order_code,
                    'phone': item.phone
                }
                print(f"dict ={dict}")
                list.append(dict)
        print(f"list ={list}")
        res_dic = {
            'list': list
        }
    return JsonResponse({'code': 200, 'data': res_dic})


# 上传评论
@check_login
def submit_order_view(request):
    print("*****************")
    data = json.loads(request.body)
    content = data.get('content')
    date_time = data.get('date_time')
    phone = data.get('phone')
    order_code = data.get('order_code')
    order = Order.objects.get(order_code=order_code)
    if not content:
        return JsonResponse({'code': 10102, 'error': '评价内容不能位空!'})
    if phone:
        if len(phone) != 11:
            return JsonResponse({'code': 10101, 'error': '请输入正确手机位数!'})
    try:
        Evaluation.objects.create(
            content=content,
            phone=phone,
            date_time=date_time,
            order=order,
        )
        return JsonResponse({'code': 200})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 10103, 'error': '评论创建失败!'})
